package com.firstresponder.activity;

import java.util.ArrayList;
import java.util.Collections;

import com.firstresponder.bluetooth.BluetoothService;
import com.firstresponder.util.SmsReceiver;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothScreen extends Activity {

	private String TAG = "BLUETOOTHSERVICE TEST";
	private static final int ALERT_MSG_TYPE = 1;
	private static final int WAIT_MSG_TYPE = 2;
	private boolean buttonStatus = false;
	private BluetoothAdapter TestAdapter;
	private ProgressDialog dialog = null;
	private Intent serviceintent = null;
	private TextView TitleText, TimerText, NumDeviceText;
	private ArrayList<TextView> textViewList = null;
	private ViewGroup linearlayout, bottom_layout;
	private Button stopButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "OnCreate Called");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bluetoothscreen);
		textViewList = new ArrayList<TextView>();
		View layout = findViewById(R.id.linear_layout);
		linearlayout = (ViewGroup) layout;
		layout = findViewById(R.id.bottom_layout);
		bottom_layout = (ViewGroup) layout;
		TitleText = (TextView) findViewById(R.id.log_title);
		TimerText = (TextView) findViewById(R.id.timer_text);
		TimerText.setTextColor(Color.YELLOW);
		NumDeviceText = (TextView) findViewById(R.id.num_device_text);
		NumDeviceText.setTextColor(Color.GREEN);
		stopButton = (Button) findViewById(R.id.stopButton);
		stopButton.setTextColor(Color.RED);
		stopButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!buttonStatus) {
					stopButton.setTextColor(Color.BLUE);
					Log.i(TAG, "Service About to stop");
					stopButton.setText("RESTART");
					stopService(serviceintent);
					Toast.makeText(BluetoothScreen.this, "SERVICE STOPPED",
							Toast.LENGTH_SHORT).show();
					TimerText.setText("0");
					Log.i(TAG, "Service Stopped");
					buttonStatus = true;
				} else {
					stopButton.setTextColor(Color.RED);
					stopButton.setText("STOP");
					startService(serviceintent);
					Toast.makeText(BluetoothScreen.this, "SERVICE RESTARTED",
							Toast.LENGTH_SHORT).show();
					buttonStatus = false;
				}
			}
		});

		serviceintent = new Intent(this, BluetoothService.class);
		TestAdapter = BluetoothAdapter.getDefaultAdapter();
		if (TestAdapter == null) {
			Log.i(TAG, "This is not a Bluetooth capable device");
		} else {
			if (!TestAdapter.isEnabled()) {
				// Wait until adapter is fully enabled before starting service
				waitForEnable();
				Log.i(TAG, "Bluetooth enabled");
			}
			Log.i(TAG, "Service is about to get activated");
			//BluetoothService.setMainActivityB(this);
			//Orginally bind the test bluetoothScreen Activity to the service
			//SmsReceiver.setMainActivity(this);
			TitleText.append(TestAdapter.getAddress());
			if (BluetoothService.isRunning() == false) {
				Log.i(TAG, "STARTING SERVICE");
				startService(serviceintent);
				BluetoothService.setIsRunning(true);
				Log.i(TAG, "SERVICE IS ACTIVATED");
			} 
			else if(!TestAdapter.isDiscovering()){
				UpdateUI("Waiting for Next Discovery Period...", 2);
			}
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		SmsReceiver.setMainActivity(null);
		// stopService(serviceintent);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		savedInstanceState.putString("deviceCount", (String)NumDeviceText.getText());
		savedInstanceState.putString("timerText",(String)TimerText.getText());
		for(TextView view : textViewList){
			linearlayout.removeView(view);
		}
		savedInstanceState.putParcelableArrayList("textViews", (ArrayList<? extends Parcelable>) textViewList);
		super.onSaveInstanceState(savedInstanceState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		NumDeviceText.setText(savedInstanceState.getString("deviceCount"));
		TimerText.setText(savedInstanceState.getString("timerText"));
		ArrayList<? extends Parcelable> savedList = savedInstanceState.getParcelableArrayList("textViews");
		//for(Object view : savedList){
		for(int i=savedList.size()-1; i>=0 ;i--){
			TextView currentView = (TextView) savedList.get(i);
			if(textViewList.size()<=12){
				textViewList.add(currentView);
				linearlayout.addView(currentView);
			}
		}
	}

	public void UpdateUI(String text, int type) {
		Log.i(TAG, "Appending Text");
		TextView logText2 = new TextView(this);
		logText2.append("B_SERVICE: " + text + "\n");
		if (type == ALERT_MSG_TYPE) {
			logText2.setTextColor(Color.RED);
		}
		else if(type == WAIT_MSG_TYPE){
			logText2.setTextColor(Color.GREEN);
		}
		linearlayout.addView(logText2, 1);
		if(textViewList.size()<=12){
			textViewList.add(logText2);
		}
		int count = linearlayout.getChildCount();
		if (count > 13) {
			linearlayout.removeViewAt(count - 1);
		}
	}

	private void waitForEnable() {
		int timeoutCounter = 0;
		Log.i(TAG, "SHOWING DIALOG");
		Log.i(TAG, "TIMEOUT COUNTER STARTED");
		TestAdapter.enable();
		while (!TestAdapter.isEnabled() && timeoutCounter != 5000) {
			SystemClock.sleep(200);
			timeoutCounter += 200;
		}
		if (timeoutCounter == 5000) {
			//Currently, the timeout is set to close the activity completely
			finishScreenActivity("BLUETOOTH ADAPTER NOT RESPONDING... Closing Application");
			
			//This section of code is the first pass of the restart 
			//functionality, which would restart the entire activity
			//in an attempt to restart the bluetooth interface
			
//			Intent intent = getIntent();
//			overridePendingTransition(0, 0);
//			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
//			Log.i(TAG, "CALLING FINISH");
//			finish();
//			overridePendingTransition(0, 0);
//			startActivity(intent);
		}
	}

	public void UpdateDevices(int numOfDevices) {
		NumDeviceText.setText(Integer.toString(numOfDevices));
	}

	// Temporarily implemented to try and stop activity from BlueSmsReceiver
	public void finishScreenActivity(String dialogMessage) {
		dialog = new ProgressDialog(this);
		dialog.setMessage(dialogMessage);
		dialog.setCancelable(false);
		dialog.show();
		new CountDownTimer(5000, 1000) {
			public void onTick(long millisUntilFinished) {
			}

			public void onFinish() {
				dialog.dismiss();
				finish();
			}
		}.start();
	}

	public void updateTimerText(String text) {
		TimerText.setText(text);
	}
}
